package com.blic.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONException;


@Component
public class CSCTokenHelper {
	private long curJSTokenTime = 0l;
	private int expiresJSToken = 0;
	private String curJSToken = null;
	public String jsapi_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	
	@Value("${tokenUrl:}")
	public String tokenURL = "http://handshake.amropchina.com.cn/csc/token/getToken";
	@Value("${appID:}")
	public String appID;
	
	public static void main(String[] args) {
		// JSONObject object =
		// WeixinUtil.singleHttpRequest("http://handshake.amropchina.com.cn/csc/token/getToken",
		// "GET", null);
		System.out.println(new CSCTokenHelper().getJsapiTicket());
	}

	/**
	 * 程序中访问http数据接口
	 */
	public static String getTokenContent(String urlStr) {
		/** 网络的url地址 */
		URL url = null;
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		try {
			url = new URL(urlStr);
			in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
			String str = null;
			while ((str = in.readLine()) != null) {
				sb.append(str);
			}
		} catch (Exception ex) {

		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		String result = sb.toString();
		System.out.println(result);
		if(result != null){
			result = DesUtil.decode(result, DesUtil.DESUTIL_KEY);
		}
		//result = "HD91F9sxHtmqfFKje7CNbjd0g3fuMLmxRgDRcIe3YEfF4tVjHsHy3Hy35EX_bcv3UGaXJqqir-jhnAb3K4h6WmRZ90XTwzHVZKktZBRYCPbWFbhBt9t3JetDPH5h36feDJSfAJAPVE";
		return result;
	}
	/**
	 * 根据token 获取ticket
	 * @param token
	 * @return
	 */
	public String getJsapiTicket() {  
	    long now = System.currentTimeMillis();  
	    if(now - curJSTokenTime > expiresJSToken*1000)  
	    {  
	        String requestUrl = jsapi_ticket.replace("ACCESS_TOKEN", getTokenContent(tokenURL));  
	        com.alibaba.fastjson.JSONObject jsonObject = WeixinUtil.singleHttpRequest(requestUrl, "GET", null);  
	        System.out.println("Getting weixin js_token...URL:"+requestUrl);  
	  
	        if (null != jsonObject) {  
	            try {  
	                curJSToken = jsonObject.getString("ticket");  
	                expiresJSToken = jsonObject.getIntValue("expires_in");  
	                curJSTokenTime = System.currentTimeMillis();  
	                System.out.println("update weixin token:"+curJSToken+"expires_in is:"+expiresJSToken+" curTime:"+curJSTokenTime);  
	            } catch (JSONException e) {  
	                System.out.println("Get JS_Token Error! errcode:{} errmsg:{}"+jsonObject.getIntValue("errcode")+jsonObject.getString("errmsg")+e);  
	            }  
	        } else {  
	            System.out.println("http for weixin return null");  
	            curJSToken="";  
	        }  
	    }   
	    return curJSToken;  
	}  
	
	public  Map<String, String> makeWXTicket(String jsapi_ticket, String url) {  
	    Map<String, String> ret = new HashMap<String, String>();  
	    String nonce_str = create_nonce_str();  
	    String timestamp = create_timestamp();  
	    String string1;  
	    String signature = "";  
	  
	    //注意这里参数名必须全部小写，且必须有序  
	    string1 = "jsapi_ticket=" + jsapi_ticket +  
	              "&noncestr=" + nonce_str +  
	              "&timestamp=" + timestamp +  
	              "&url=" + url;  
	    try  
	    {  
	    	MessageDigest crypt = MessageDigest.getInstance("SHA-1");  
	        crypt.reset();  
	        crypt.update(string1.getBytes("UTF-8"));  
	        signature = byteToHex(crypt.digest());  
	    }  
	    catch (NoSuchAlgorithmException e)  
	    {  
	        e.printStackTrace();  
	    }  
	    catch (UnsupportedEncodingException e)  
	    {  
	        e.printStackTrace();  
	    }  
	  
	    ret.put("url", url);  
	    ret.put("jsapi_ticket", jsapi_ticket);  
	    ret.put("nonceStr", nonce_str);  
	    ret.put("timestamp", timestamp);  
	    ret.put("signature", signature);  
	    ret.put("appid",appID);  
	  
	    return ret;  
	}  
	  
	private static String byteToHex(final byte[] hash) {  
	    Formatter formatter = new Formatter();  
	    for (byte b : hash)  
	    {  
	        formatter.format("%02x", b);  
	    }  
	    String result = formatter.toString();  
	    formatter.close();  
	    return result;  
	}  
	  
	private static String create_nonce_str() {  
	    return UUID.randomUUID().toString();  
	}  
	  
	private static String create_timestamp() {  
	    return Long.toString(System.currentTimeMillis() / 1000);  
	}  

}
